﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System.Management;

/// <summary>
///LogicLayer 的摘要说明
/// </summary>
public partial class LogicLayer
{
    #region Construct
    public LogicLayer()
	{
	}
    #endregion

    #region Users
    /// <summary>
    /// 登录
    /// </summary>
	/// <returns>-1 failed 0 success 1 failed 2 nolic </returns>
    public int Logon(string userName, string userPwd, HttpContext context)
    {
        try
        {
			if (!VerifyLicense())
				return 2;

            int result = 0;

            string enPwd = userPwd;
            if (!string.IsNullOrEmpty(userPwd))
            {
                QF.Security.Cryptographyer crypt = new QF.Security.Cryptographyer();
                enPwd = crypt.EncryptData(userPwd);
            }

            //Database db = DatabaseFactory.CreateDatabase();
            Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("connStr");

            string sql = "select count(*) from SYS_User where UserName=@UserName and Password=@UserPwd and Disabled=0";
            DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@UserName", DbType.String, userName);
            db.AddInParameter(cmd, "@UserPwd", DbType.String, enPwd);

            int n = (int)db.ExecuteScalar(cmd);
            if (n > 0)
                context.Session["CurrentUserName"] = userName;
            else
                result = 1;

            return result;
        }
        catch(Exception ex) {
			//Logger.Write(new LogEntry() { Categories="General", Message=ex.Message, TimeStamp=DateTime.Now, Severity=System.Diagnostics.TraceEventType.Error});
            Logger.Write("LogicLayer.Login:" + ex.Message);
            return -1;
        }
    }

    /// <summary>
    /// 注销
    /// </summary>
    public void Logoff(HttpContext context)
    {
        try
        {
            context.Session.Remove("CurrentUserName");
        }
        catch { }
    }

    /// <summary>
    /// 得到人员的用户名
    /// </summary>
    public string GetUserNameByEmplID(string emplID)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "select UserName from SYS_UserEmpl where EmplID=@EmplID";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@EmplID", DbType.String, emplID);

            return (string)db.ExecuteScalar(cmd);
        }
        catch (Exception ex)
        {
            Logger.Write("GetUserNameByEmplID:" + ex.Message);
            return string.Empty;
        }
    }

	/// <summary>
	/// 禁用/启用用户
	/// </summary>
	public bool UpdateUser(string userName, int disabled)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "update SYS_User set Disabled=@Disabled where UserName=@UserName";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);

			db.AddInParameter(cmd, "@Disabled", DbType.Int32, disabled);
			db.AddInParameter(cmd, "@UserName", DbType.String, userName);

			db.ExecuteNonQuery(cmd);
			return true;
		}
		catch (Exception ex)
		{
			Logger.Write("UpdateUser:" + ex.Message);
			return false;
		}
	}

	/// <summary>
	/// 添加用户(并添加对应的人员)
	/// </summary>
	public bool AddUser(SYS_User theSYS_User, string emplID)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");

			string sql = "insert into SYS_User (UserName,Password,LastModifiedTime,LastModifiedByID,LastRefresh,Disabled) values (@UserName,@Password,@LastModifiedTime,@LastModifiedByID,@LastRefresh,@Disabled)";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);

			db.AddInParameter(cmd, "@UserName", DbType.String, theSYS_User.UserName);
			QF.Security.Cryptographyer crypt = new QF.Security.Cryptographyer();
			if(!string.IsNullOrEmpty(theSYS_User.Password.Trim()))
				theSYS_User.Password = crypt.EncryptData(theSYS_User.Password);
			db.AddInParameter(cmd, "@Password", DbType.String, theSYS_User.Password);
			db.AddInParameter(cmd, "@LastModifiedTime", DbType.DateTime, theSYS_User.LastModifiedTime);
			db.AddInParameter(cmd, "@LastModifiedByID", DbType.String, theSYS_User.LastModifiedByID);
			db.AddInParameter(cmd, "@LastRefresh", DbType.DateTime, theSYS_User.LastRefresh);
			db.AddInParameter(cmd, "@Disabled", DbType.Int32, theSYS_User.Disabled);

			db.ExecuteNonQuery(cmd);

			//添加对应的人员
			cmd.CommandText = "insert into SYS_UserEmpl (UserName,EmplID) values (@UserName,@EmplID)";
			cmd.Parameters.Clear();
			db.AddInParameter(cmd, "@UserName", DbType.String, theSYS_User.UserName);
			db.AddInParameter(cmd, "@EmplID", DbType.String, emplID);
			db.ExecuteNonQuery(cmd);

			return true;
		}
		catch (Exception ex)
		{
			Logger.Write("AddUser:" + ex.Message);
			return false;
		}
	}

	public bool IsUserNameRepeat(string userName)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");

			string sql = "select count(*) from SYS_User where UserName=@UserName";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);

			db.AddInParameter(cmd, "@UserName", DbType.String, userName);
			int r = (int)db.ExecuteScalar(cmd);
			if (r > 0)
				return true;
			else
				return false;
		}
		catch (Exception ex)
		{
			Logger.Write("IsUserNameRepeat:" + ex.Message);
			return false;
		}
	}
    #endregion

    #region Function

    public bool VerifyFunction(string functionID, string userName)
    {
        try
        {
            if (string.Compare(userName, "admin", true) == 0)
                return true;

            string sql = "select COUNT(*) from SYS_RoleFunction rf ,SYS_RoleUser ru where rf.FunctionID=@FunctionID and ru.UserName=@UserName and rf.RoleID=ru.RoleID";

            Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("connStr");
            DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@UserName", DbType.String, userName);
            db.AddInParameter(cmd, "@FunctionID", DbType.String, functionID);

            int n = (int)db.ExecuteScalar(cmd);

            if (n > 0)
                return true;
            else
                return false;
        }
        catch (Exception ex)
        {
            Logger.Write("LogicLayer.VerifyFunction:" + ex.Message);
            return false;
        }
    }

	public List<SYS_Function> ListFunctions()
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select * from SYS_Function order by Tag, Name";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);

			List<SYS_Function> result = new List<SYS_Function>();
			using (IDataReader dataReader = db.ExecuteReader(cmd))
			{
				while (dataReader.Read())
				{
					SYS_Function obj = GetSYS_FunctionFromDataReader(dataReader);
					if (obj != null)
						result.Add(obj);
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("ListFunctions:" + ex.Message);
			return null;
		}
	}

	/// <summary>
	/// 得到角色的功能ID
	/// </summary>
	public List<string> ListFunctionID(string roleID)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select FunctionID from SYS_RoleFunction where RoleID=@RoleID";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@RoleID", DbType.String, roleID);

			List<string> result = new List<string>();
			using (IDataReader dataReader = db.ExecuteReader(cmd))
			{
				while (dataReader.Read())
				{
					result.Add(dataReader.GetString(0));
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("ListFunctionID:" + ex.Message);
			return null;
		}
	}

	public bool DelRoleFunctions(string RoleID)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "delete From SYS_RoleFunction where RoleID=@RoleID ";

			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@RoleID", DbType.String, RoleID);

			db.ExecuteNonQuery(cmd);
			return true;
		}
		catch (Exception ex)
		{
			Logger.Write("DelRoleFunctions:" + ex.Message);
			return false;
		}
	}
    #endregion

    #region Department
    public List<SYS_Department> ListDeptByParent(string parentID)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "select * from SYS_Department where ParentID=@ParentID and Disabled=0 order by DeptNo";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@ParentID", DbType.String, parentID);

            List<SYS_Department> result = new List<SYS_Department>();
            using (IDataReader dataReader = db.ExecuteReader(cmd))
            {
                while (dataReader.Read())
                {
                    SYS_Department obj = GetSYS_DepartmentFromDataReader(dataReader);
                    if (obj != null)
                        result.Add(obj);
                }
            }
            return result;
        }
        catch (Exception ex)
        {
            Logger.Write("ListSYS_Department:" + ex.Message);
            return null;
        }
    }

    public bool HasChildDept(string deptID)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "select count(*) from SYS_Department where ParentID=@ParentID and Disabled=0";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@ParentID", DbType.String, deptID);

            int n = (int)db.ExecuteScalar(cmd);
            if (n > 0)
                return true;
            else
                return false;
        }
        catch (Exception ex)
        {
            Logger.Write("HasChildDept:" + ex.Message);
            return false;
        }
    }

    public int GetChildDeptCount(string deptID)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "select count(*) from SYS_Department where ParentID=@ParentID and Disabled=0";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@ParentID", DbType.String, deptID);

            return  (int)db.ExecuteScalar(cmd);
        }
        catch (Exception ex)
        {
            Logger.Write("GetChildDeptCount:" + ex.Message);
            return 0;
        }
    }

    /// <summary>
    /// 删除部门，同时删除下属部门，调整部门人员
    /// </summary>
    public bool DelDepartment(string deptID)
    {
        try
        {
            //get child deptid
            string childDeptID = GetChildDeptIDString(deptID, true);

            Database db = DatabaseFactory.CreateDatabase("connStr");

            //disable current dept
            string sql = "update SYS_Department set Disabled=1 where DeptID=@DeptID";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@DeptID", DbType.String, deptID);
            db.ExecuteNonQuery(cmd);
            
            //move current dept users
            cmd.CommandText = "delete SYS_EmplDept where DeptID=@DeptID";
            db.ExecuteNonQuery(cmd);

            //disable child dept
            cmd.CommandText = "update SYS_Department set Disabled=1 where DeptID in ('" + childDeptID.Replace(",","','") + "')";
            cmd.Parameters.Clear();
            db.ExecuteNonQuery(cmd);

            //move child dept users
            cmd.CommandText = "delete SYS_EmplDept where DeptID in ('" + childDeptID.Replace(",", "','") + "')";
            db.ExecuteNonQuery(cmd);

            return true;
        }
        catch (Exception ex)
        {
            Logger.Write("DelDepartment:" + ex.Message);
            return false;
        }
    }

    /// <summary>
    /// 得到子部门的ID字符串
    /// </summary>
    /// <param name="includeSubChild">是否包含下级子部门</param>
    /// <returns>逗号分割，如 0001,0002,0003</returns>
    public string GetChildDeptIDString(string parentID, bool includeSubChild)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "select DeptID from SYS_Department where ParentID=@ParentID and Disabled=0";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@ParentID", DbType.String, parentID);

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            List<string> idList = new List<string>();
            using (IDataReader dataReader = db.ExecuteReader(cmd))
            {
                while (dataReader.Read())
                {
                    idList.Add(dataReader.GetString(0));
                    sb.Append("," + dataReader.GetString(0));
                }
            }

            if (includeSubChild)
            {
                string temp = string.Empty;
                foreach (string childID in idList)
                {
                    temp = GetChildDeptIDString(childID, includeSubChild);
                    if (!string.IsNullOrEmpty(temp))
                        sb.Append("," + temp);
                }
            }

            string result = sb.ToString();
            if (result.Length > 1)
                result = result.Substring(1);

            return result;
        }
        catch (Exception ex)
        {
            Logger.Write("GetChildDeptIDString:" + ex.Message);
            return string.Empty;
        }
    }

    /// <summary>
    /// 得到人员所在部门的名称
    /// </summary>
    public string GetDeptNameByEmplID(string emplID)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "select d.DeptName from SYS_EmplDept ed, SYS_Department d where ed.EmplID=@EmplID and ed.DeptID=d.DeptID";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@EmplID", DbType.String, emplID);

            string result = string.Empty;
            using (IDataReader dataReader = db.ExecuteReader(cmd))
            {
                while (dataReader.Read())
                {
                    result += "," + dataReader.GetString(0);
                }
            }
            if (result.IndexOf(",") > -1)
                result = result.Substring(1);

            return result;
        }
        catch (Exception ex)
        {
            Logger.Write("GetDeptNameByEmplID:" + ex.Message);
            return string.Empty;
        }
    }

	/// <summary>
	/// 得到人员所在部门的名称
	/// </summary>
	public string GetDeptIDByEmplID(string emplID)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select DeptID from SYS_EmplDept where EmplID=@EmplID ";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@EmplID", DbType.String, emplID);

			string result = string.Empty;
			using (IDataReader dataReader = db.ExecuteReader(cmd))
			{
				if (dataReader.Read())
				{
					result = dataReader.GetString(0);
				}
			}

			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("GetDeptIDByEmplID:" + ex.Message);
			return string.Empty;
		}
	}

	public bool UpdateDeptNo(string deptID, string deptNo)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "update SYS_Department set DeptNo=@DeptNo where DeptID=@DeptID";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);

			db.AddInParameter(cmd, "@DeptNo", DbType.String, deptNo);
			db.AddInParameter(cmd, "@DeptID", DbType.String, deptID);

			db.ExecuteNonQuery(cmd);
			return true;
		}
		catch (Exception ex)
		{
			Logger.Write("UpdateDeptNo:" + ex.Message);
			return false;
		}
	}

	public bool SortDept( System.Collections.Hashtable hash)
	{
		try
		{
			bool result = true;
			System.Collections.IDictionaryEnumerator enumerator = hash.GetEnumerator();
			while (enumerator.MoveNext())
			{
				result &= UpdateDeptNo(enumerator.Key.ToString(), enumerator.Value.ToString());
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("SortDept:" + ex.Message);
			return false;
		}
	}
    
    #endregion

    #region Employee

    /// <summary>
    /// 添加人员（同时添加用户）
    /// </summary>
    public bool AddEmployee(SYS_Employee theEmployee, SYS_User theUser)
    {
        try
        {
            bool result = false;

            //add employee
            if (AddSYS_Employee(theEmployee))
            {
                QF.Security.Cryptographyer crypt = new QF.Security.Cryptographyer();

                theUser.Password = crypt.EncryptData(theUser.Password);

                // add user
                if (AddSYS_User(theUser))
                {
                    SYS_UserEmpl ue = new SYS_UserEmpl();
                    ue.EmplID = theEmployee.EmplID;
                    ue.UserName = theUser.UserName;

                    // add user-empl
                    if (AddSYS_UserEmpl(ue))
                        result = true;
                }
            }

            return result;
        }
        catch (Exception ex)
        {
            Logger.Write("AddEmployee:" + ex.Message);
            return false;
        }
    }

	/// <summary>
	/// 禁用人员
	/// </summary>
    public bool DisableEmployee(string EmplID)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "update SYS_Employee set disabled=1 where EmplID=@EmplID";

            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@EmplID", DbType.String, EmplID);

            db.ExecuteNonQuery(cmd);
            return true;
        }
        catch (Exception ex)
        {
            Logger.Write("DisableEmployee:" + ex.Message);
            return false;
        }
    }

	/// <summary>
	/// 列出全部人员
	/// </summary>
    public List<SYS_Employee> ListEmployees()
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "select * from SYS_Employee where disabled=0 ";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);

            List<SYS_Employee> result = new List<SYS_Employee>();
            using (IDataReader dataReader = db.ExecuteReader(cmd))
            {
                while (dataReader.Read())
                {
                    SYS_Employee obj = GetSYS_EmployeeFromDataReader(dataReader);
                    if (obj != null)
                        result.Add(obj);
                }
            }
            return result;
        }
        catch (Exception ex)
        {
            Logger.Write("ListSYS_Employee:" + ex.Message);
            return null;
        }
    }

	public List<SYS_Employee> FindEmployees(string queryText)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select * from SYS_Employee where disabled=0 and EmplName like @EmplName ";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@EmplName", DbType.String, "%" + queryText + "%");

			List<SYS_Employee> result = new List<SYS_Employee>();
			using (IDataReader dataReader = db.ExecuteReader(cmd))
			{
				while (dataReader.Read())
				{
					SYS_Employee obj = GetSYS_EmployeeFromDataReader(dataReader);
					if (obj != null)
						result.Add(obj);
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("FindEmployees:" + ex.Message);
			return null;
		}
	}

	/// <summary>
	/// 列出角色对应的人员
	/// </summary>
	public List<SYS_Employee> ListEmployeeByRoleID(string roleID)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "select e.* from SYS_EmplRole er, SYS_Employee e where e.Disabled=0 and er.EmplID=e.EmplID and er.RoleID=@RoleID";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@RoleID", DbType.String, roleID);

            List<SYS_Employee> result = new List<SYS_Employee>();
            using (IDataReader dataReader = db.ExecuteReader(cmd))
            {
                while (dataReader.Read())
                {
                    SYS_Employee obj = GetSYS_EmployeeFromDataReader(dataReader);
                    if (obj != null)
                        result.Add(obj);
                }
            }
            return result;
        }
        catch (Exception ex)
        {
			Logger.Write("ListEmployeeByRoleID:" + ex.Message);
            return null;
        }
    }

	/// <summary>
	/// 列出部门的下属人员
	/// </summary>
	public List<SYS_Employee> ListEmployeeByDeptID(string deptID)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select e.* from SYS_EmplDept ed, SYS_Employee e where e.Disabled=0 and ed.EmplID=e.EmplID and ed.DeptID=@DeptID";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@DeptID", DbType.String, deptID);

			List<SYS_Employee> result = new List<SYS_Employee>();
			using (IDataReader dataReader = db.ExecuteReader(cmd))
			{
				while (dataReader.Read())
				{
					SYS_Employee obj = GetSYS_EmployeeFromDataReader(dataReader);
					if (obj != null)
						result.Add(obj);
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("ListEmployeeByDeptID:" + ex.Message);
			return null;
		}
	}

	/// <summary>
	/// 列出没有分配部门的人员
	/// </summary>
	public List<SYS_Employee> ListEmployeeNoDeptID()
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select * from SYS_Employee where disabled=0 and emplid not in (select EmplID from SYS_EmplDept)";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);

			List<SYS_Employee> result = new List<SYS_Employee>();
			using (IDataReader dataReader = db.ExecuteReader(cmd))
			{
				while (dataReader.Read())
				{
					SYS_Employee obj = GetSYS_EmployeeFromDataReader(dataReader);
					if (obj != null)
						result.Add(obj);
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("ListEmployeeNoDeptID:" + ex.Message);
			return null;
		}
	}

	/// <summary>
	/// 得到用户对应的人员
	/// </summary>
	public SYS_Employee GetEmployeeByUserName(string userName)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select e.* From SYS_Employee e, SYS_UserEmpl ue where ue.UserName=@UserName and e.EmplID=ue.EmplID";

			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@UserName", DbType.String, userName);

			SYS_Employee result = null;
			using (IDataReader dataReader = db.ExecuteReader(cmd))
			{
				if (dataReader.Read())
				{
					result = GetSYS_EmployeeFromDataReader(dataReader);
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("GetEmployeeByUserName:" + ex.Message);
			return null;
		}
	}
	
    #endregion

    #region Position

    /// <summary>
    /// 得到人员的职位
    /// </summary>
    public string GetPositionNameByEmplID(string emplID)
    {
        try
        {
            Database db = DatabaseFactory.CreateDatabase("connStr");
            string sql = "select p.Name from SYS_Position p,sys_EmplPosition ep where ep.EmplID=@EmplID and p.PositionID=ep.PositionID";
            System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@EmplID", DbType.String, emplID);

            return (string)db.ExecuteScalar(cmd);
        }
        catch (Exception ex)
        {
            Logger.Write("GetPositionNameByEmplID:" + ex.Message);
            return string.Empty;
        }
    }
    #endregion

	#region Role
	public List<SYS_Role> ListRoles()
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select * from SYS_Role where Disabled=0 order by LastModifiedTime";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);

			List<SYS_Role> result = new List<SYS_Role>();
			using (IDataReader dataReader = db.ExecuteReader(cmd))
			{
				while (dataReader.Read())
				{
					SYS_Role obj = GetSYS_RoleFromDataReader(dataReader);
					if (obj != null)
						result.Add(obj);
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("ListRoles:" + ex.Message);
			return null;
		}
	}

	public List<SYS_Role> FindRoles(string queryText)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select * from SYS_Role where Disabled=0 and Name like @Name order by LastModifiedTime";
			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@Name", DbType.String, "%" + queryText + "%");

			List<SYS_Role> result = new List<SYS_Role>();
			using (IDataReader dataReader = db.ExecuteReader(cmd))
			{
				while (dataReader.Read())
				{
					SYS_Role obj = GetSYS_RoleFromDataReader(dataReader);
					if (obj != null)
						result.Add(obj);
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("FindRoles:" + ex.Message);
			return null;
		}
	}

	/// <summary>
	/// 删除角色（同时删除对应的功能，对应的人员）
	/// </summary>
	public bool DelRole(string RoleID)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "delete From SYS_Role where RoleID=@RoleID";

			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.AddInParameter(cmd, "@RoleID", DbType.String, RoleID);

			db.ExecuteNonQuery(cmd);

			cmd.CommandText = "delete SYS_RoleFunction where RoleID=@RoleID";
			db.ExecuteNonQuery(cmd);

			cmd.CommandText = "delete SYS_EmplRole where RoleID=@RoleID";
			db.ExecuteNonQuery(cmd);

			return true;
		}
		catch (Exception ex)
		{
			Logger.Write("DelRole:" + ex.Message);
			return false;
		}
	}
	#endregion

	#region EmplDept
	/// <summary>
	/// 添加人员部门(先清除再添加)
	/// </summary>
	public bool AddEmplDept(string emplID, string deptID, bool clearFirst)
	{
		try
		{
			
			Database db = DatabaseFactory.CreateDatabase("connStr");

			if (clearFirst)
			{
				string sql = "delete SYS_EmplDept where EmplID=@EmplID";
				System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
				db.AddInParameter(cmd, "@EmplID", DbType.String, emplID);
				db.ExecuteNonQuery(cmd);

				cmd.CommandText = "insert into SYS_EmplDept (EmplID,DeptID) values (@EmplID,@DeptID)";
				cmd.Parameters.Clear();
				db.AddInParameter(cmd, "@EmplID", DbType.String, emplID);
				db.AddInParameter(cmd, "@DeptID", DbType.String, deptID);
				db.ExecuteNonQuery(cmd);
			}
			else
			{
				string sql = "insert into SYS_EmplDept (EmplID,DeptID) values (@EmplID,@DeptID)";
				System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
				db.AddInParameter(cmd, "@EmplID", DbType.String, emplID);
				db.AddInParameter(cmd, "@DeptID", DbType.String, deptID);
				db.ExecuteNonQuery(cmd);
			}
			return true;
		}
		catch (Exception ex)
		{
			Logger.Write("AddEmplDept:" + ex.Message);
			return false;
		}
	}
	#endregion

	#region EmplPosition

	/// <summary>
	/// 添加人员职位（先清除再添加）
	/// </summary>
	public bool AddEmplPosition(string emplID, string positionID, bool clearFirst)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");

			if (clearFirst)
			{
				string sql = "delete SYS_EmplPosition where EmplID=@EmplID";
				System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
				db.AddInParameter(cmd, "@EmplID", DbType.String, emplID);
				db.ExecuteNonQuery(cmd);

				cmd.CommandText = "insert into SYS_EmplPosition (EmplID,PositionID) values (@EmplID,@PositionID)";
				cmd.Parameters.Clear();
				db.AddInParameter(cmd, "@EmplID", DbType.String, emplID);
				db.AddInParameter(cmd, "@PositionID", DbType.String, positionID);
				db.ExecuteNonQuery(cmd);
			}
			else
			{
				string sql = "insert into SYS_EmplPosition (EmplID,PositionID) values (@EmplID,@PositionID)";
				System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
				db.AddInParameter(cmd, "@EmplID", DbType.String, emplID);
				db.AddInParameter(cmd, "@PositionID", DbType.String, positionID);
				db.ExecuteNonQuery(cmd);
			}

			return true;
		}
		catch (Exception ex)
		{
			Logger.Write("AddEmplPosition:" + ex.Message);
			return false;
		}
	}
	#endregion

	#region License

	public string GetLicenseData()
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "select * From SYS_License ";

			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);

			string result = "";
			using (IDataReader dataReader = db.ExecuteReader(cmd))
			{
				if (dataReader.Read())
				{
					result = dataReader.GetString(0);
				}
			}
			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("GetLicenseData:" + ex.Message);
			return "";
		}
	}

	public string GetCam()
	{
		try
		{
			string result = string.Empty;

			ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
			ManagementObjectCollection queryCollection = query.Get();

			string mac = string.Empty;
			foreach (ManagementObject mo in queryCollection)
			{
				if (mo["IPEnabled"].ToString() == "True" && mo["ServiceName"].ToString() != "VMnetAdapter")
					mac = mo["MacAddress"].ToString();
				else
					mac = "";

				if (!string.IsNullOrEmpty(mac))
				{
					result = string.Empty;
					string[] array = mac.Split(':');
					for (int i = array.Length - 1; i >= 0; i--)
					{
						result += array[i];
					}
					if (!string.IsNullOrEmpty(result))
						break;
				}
			}
			if (!string.IsNullOrEmpty(result))
				result = "QF-" + result;

			return result;
		}
		catch (Exception ex)
		{
			Logger.Write("GetCam:" + ex.Message);
			return "";
		}
	}

	public bool VerifyLicense()
	{
		string lic = GetLicenseData();

		string cam = GetCam();

		if (string.IsNullOrEmpty(lic) || string.IsNullOrEmpty(cam))
			return false;

		QF.Security.Cryptographyer crypt = new QF.Security.Cryptographyer();

		if (string.Compare(crypt.EncryptData(cam), lic) == 0)
			return true;
		else
			return false;
	}

	public bool SubmitLicense(string licKey)
	{
		string lic = licKey;

		string cam = GetCam();

		if (string.IsNullOrEmpty(lic) || string.IsNullOrEmpty(cam))
			return false;

		QF.Security.Cryptographyer crypt = new QF.Security.Cryptographyer();
		if (string.Compare(crypt.EncryptData(cam), lic) == 0)
		{
			return UpdateLicense(licKey);
		}
		else
			return false;
	}

	public bool UpdateLicense(string licKey)
	{
		try
		{
			Database db = DatabaseFactory.CreateDatabase("connStr");
			string sql = "delete From SYS_License ";

			System.Data.Common.DbCommand cmd = db.GetSqlStringCommand(sql);
			db.ExecuteNonQuery(cmd);

			cmd.CommandText = "insert into SYS_License (LicData) values (@LicData)";
			db.AddInParameter(cmd, "@LicData", DbType.String, licKey);
			db.ExecuteNonQuery(cmd);

			return true;
		}
		catch (Exception ex)
		{
			Logger.Write("UpdateLicense:" + ex.Message);
			return false;
		}
	}
	#endregion
}